<template><!--创建问题-->
    <div class="warp-2" style="height:100%;padding-top: 56px;box-sizing: border-box;">
        <van-nav-bar fixed class="header-title-01 header-left-btn" :title="$t('create_problem')">
            <span slot="left" class="iconfont icon-cha head-left" @click="back()"></span>
            <div slot="right">
                <span class="font-size15 write-btn-right head-right" v-if="know.queTitle.replace(/(^\s*)|(\s*$)/g, '') == '' || errors.has('tipsQueTitle') == true">{{ $t('btn_publish') }}</span><!--发布-->
                <span class="font-size15 write-btn-right head-right cur" @click="submit" v-if="know.queTitle.replace(/(^\s*)|(\s*$)/g, '') != '' && errors.has('tipsQueTitle') == false">{{ $t('btn_publish') }}</span>
            </div>
        </van-nav-bar>
        <div class="content-noBottom" :style="btnToggleMask?'padding: 0;overflow: hidden;': 'padding: 0;'">
            <div class="layer-content-box">
                <div class="add-contents-box">
                    <p class="word-title-06">{{ $t('know_que_describe') }}</p><!--问题描述(必填)-->
                    <div class="white-bg bottom-shadow">
                        <textarea v-validate="'tipsQueTitle'" name="tipsQueTitle" v-model="know.queTitle" :placeholder="$t('know_que_describe_tips')" style="height: 41px;"></textarea><!--输入详情的问题描述...-->
                        <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsQueTitle')">{{ $t('exceeded_word_range_tips', {'value': '200'}) }}</p><!--200-->
                    </div>
                    <p class="word-title-06">{{ $t('know_que_supply') }}</p><!--问题补充-->
                    <div class="white-bg">
                        <div>
                            <quill-editor
                                style="height: 300px"
                                ref="myQuillEditor"
                                v-model="content"
                                :options="editorOption"
                                @change="onEditorChange"
                            />
                        </div>
                        <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsQueDetail')">{{ $t('exceeded_word_range_tips', {'value': '1000'}) }}</p><!--1000-->
                    </div>
                </div>
                <div class="margin-top10" style="margin-bottom: 10px;">
                    <ul class="module-list-10">
                        <li class="clearfix" @click="showQuestionCategory()">
                            <span class="font-size15">{{ $t('know_ask_que_classify') }}</span><!--问题分类-->
                            <i class="arrow-right"></i>
                            <span class="color999 word-title-08">
                                <em>
                                    {{ primaryTitleShow ? primaryTitleShow : (secondaryTitleShow ? secondaryTitleShow : '') }}
                                </em>
                            </span>
                        </li>
                        <li class="clearfix" @click="selectedUser">
                            <span class="font-size15">{{ $t('know_ask_instructor') }}</span><!--邀请人回答-->
                            <i class="arrow-right"></i>
                            <span style="float: right;margin-right: 5px;">
                                <span v-if="checkedNames.length > 0">{{ $t('know_answer_select_user', {'value': checkedNames.length}) }}</span>
                                <new-select-user :is-show.sync="isShowSelectUser" @changeIdList="selectUserIdHandle" :default-selected-id-list="checkedNames"></new-select-user>
                            </span>
                        </li>
                        <li class="clearfix" @click="rewardPoint()">
                            <span class="font-size15">{{ $t('know_bounty') }}</span><!--悬赏积分-->
                            <i class="arrow-right"></i>
                            <span class="color999" style="float: right;margin-right: 5px;">{{ point }}{{ point > 1 ? $t('credits_point_num_2') : $t('credits_point_num') }}</span><!--积分-->
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <!--问题分类 start-->
        <div class="mask-layer" @click="maskLayer()" v-if="btnToggleMask"></div>
        <div class="headerSelect-alert4" v-if="primaryClassification">
            <ul>
                <li class="clearfix" :class="{'cur': know.kcaIdOne === category.kcaId}" v-for="category in questionCategory" :key="category.kcaId" @click="knowSelectClassificationOne(category.kcaId, category.childKnowCatalogList.length, category.kcaTitle)">
                    <p class="word-title-05">{{ category.kcaTitle }}<em class="arrow-icon" v-if="category.childKnowCatalogList.length > 0"></em></p>
                </li>
            </ul>
        </div>
        <div class="headerSelect-alert4" v-if="secondaryClassification">
            <ul>
                <li class="word-title-07" @click="backToPrevious()">{{ $t('know_back_to_previous') }}</li><!--返回上一级-->
                <li class="font-size15" :class="{'cur' : selectClassificationTwoOne == true && know.kcaIdTwo === 0 &&  know.kcaIdOne == selectClassificationOneTitleId }" @click="knowSelectClassificationOne(selectClassificationOneTitleId, -1, primaryTitle)">
                    {{ primaryTitle }}
                </li>
                <li class="clearfix color666" :class="{'cur': know.kcaIdTwo === category.kcaId}" v-for="category in questionSecondaryCategory" :key="category.kcaId" @click="scCategory(category.kcaId, category.kcaTitle)">
                    <p class="word-title-05">{{ category.kcaTitle }}</p>
                </li>
            </ul>
        </div>
        <!--问题分类 end-->
        <!--悬赏积分 start-->
        <van-dialog
            v-model="rewardPointLayer"
            :title="$t('know_bounty')"
            show-cancel-button
            :confirmButtonText="$t('sure')"
            :cancelButtonText="$t('cancel')"
            :before-close="beforeCloseDialog"
            >
            <p class="color999" style="font-size: 14px;">{{ $t('know_bounty_tips_1') }}</p><!--当选择最佳答案后，会自动扣除你的积分-->
            <div class="box-16">
                <p class="colorfd3 font-size11 tips"><em v-if="rewardPointTips1">{{ $t('know_bounty_tips_2') }}</em><em v-if="rewardPointTips2">{{ $t('know_bounty_tips_3') }}</em></p><!--请输入一个大于0的整数/你的积分不足-->
                <div><!--悬赏/积分-->
                    <span>{{ $t('know_reward') }}</span><span style="float: right;">{{ $t('credits_point') }}</span><input type="number" v-model="rewPoint" placeholder="0"/>
                </div>
            </div>
            <p class="font-size12 color666">{{ $t('know_credits_my_total') }}{{ credits }}</p><!--我的总积分-->
        </van-dialog>
        <!--悬赏积分 end-->
        <!-- 退出提示 -->
        <van-dialog
            v-model="leaveHint"
            :title="$t('confirm_exit_1')"
            :message="$t('confirm_exit_content_1')"
            show-cancel-button
            :confirmButtonText="$t('sure')"
            :cancelButtonText="$t('cancel')"
            @confirm="$router.go(-1)"
            >
        </van-dialog>
        <input style="position: fixed;left: -2000px;top: -2000px;" @change="handleAdd_quill_editor" id="input_hide"
               class="upload_input" type="file">
    </div>
</template>

<script>
import {appUrl} from '../../../config/loginConfig';
import NewSelectUser from '../common/NewSelectUser';
export default {
    name: 'AddQuestion',
    components: {
        NewSelectUser
    },
    data() {
        return {
            btnToggleMask: false, //问题分类弹出黑层
            primaryClassification: false, //一级分类
            selectClassificationOneTitleId: '',
            secondaryClassification: false, //二级分类
            selectClassificationTwoOne: false, //二级问题分类的一级分类
            keepClassificationOneId: null, //保存一级分类的id
            primaryTitleShow: '', //一级分类标题显示
            secondaryTitleShow: '', //二级分类标题显示
            questionCategory: [],
            questionSecondaryCategory: [], //二级问题分类
            classification: [], //选择的分类
            rewardPointLayer: false, //悬赏积分弹出框
            credits: {}, //悬赏积分
            rewardPointTips1: false,
            rewardPointTips2: false,
            rewPoint: '', //用户输入的积分
            point: '0', //填写的悬赏积分
            know: {
                kcaIdOne: '',
                kcaIdTwo: 0,
                queTitle: '',
                queContent: ''
            },
            isTop: false,
            onFetching: false,
            memberList: [],
            searchContent: '',
            isShowSelectUser: false,
            checkedNames: [],
            total: 0,
            leaveHint: false,
            upImages: [], //上传图片列表
            chooseMsg: '',
            content: '',
            editorOption: {
                modules: {
                    toolbar: {
                        container: [
                            ['bold', 'italic'], // 加粗 斜体 下划线
                            [{ header: 1 }, { header: 2 }], // 1、2 级标题
                            ['image'] // 链接、图片、视频
                        ], //工具菜单栏配置
                        handlers: {
                            'image': function(value) {
                                if (value) {
                                    document.querySelector('#input_hide').click();
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }

                },
                placeholder: this.$t('tips_1'), //提示
                readyOnly: false, //是否只读
                theme: 'snow', //主题 snow/bubble
                syntax: true //语法检测
            },
            isLoading: false
        };
    },
    methods: {
        selectUserIdHandle(data) {
            this.checkedNames = data;
        },
        handleAdd_quill_editor(ev) { // 上传富文本
            const extension = ev.target.files[0].name.split('.').pop().toLowerCase();
            const imageExtensions = ['JPEG', 'JPG', 'GIF', 'PNG', 'jpeg', 'jpg', 'gif', 'png'];
            let isImage = imageExtensions.includes(extension);
            if (!isImage) {
                this.$toast(this.$t('lab_file_tips_6'));
                return false;
            }
            let vm = this;
            let files = ev.target.files[0];
            let param = new FormData(); // 创建form对象
            param.append('file', files); // 通过append向form对象添加数据
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }; // 添加请求头
            this.$axios.post(`/app/api/file/editor`, param, config).then(response => {
                if (response.data.message === 'SUCCESS') {
                    let quillFwb = vm.$refs['myQuillEditor'].quill;
                    // 获取光标所在位置
                    let length = quillFwb.getSelection().index;
                    // 插入图片，res为服务器返回的图片链接地址
                    quillFwb.insertEmbed(length, 'image', response.data.url);
                    // 调整光标到最后
                    quillFwb.setSelection(length + 1);
                }
            });
        },
        onEditorChange({ quill, html, text }) {
            this.content = html;
        },
        back() {
            if (this.know.queTitle === '' && this.know.queContent === '' && this.know.kcaIdOne === this.questionCategory[0].kca_id && this.know.kcaIdTwo === 0 && this.rewPoint === '' && this.upImages.length < 1 && this.checkedNames.length < 1) {
                this.$router.go(-1);
            } else {
                this.leaveHint = true;
            }
        },
        questionPrimaryCategory() {
            this.$axios({
                method: 'GET',
                // url: '/app/know/allKnow/kca/CATALOG/0'
                url: `/app/api/trainee/know/kca/CATALOG/0`
            }).then((res) => {
                this.questionCategory = res.data;
            });
        },
        showQuestionCategory() { //显示分类
            this.btnToggleMask = true;
            this.primaryClassification = true;
            this.questionPrimaryCategory();
        },
        knowSelectClassificationOne(categoryId, listTotal, categoryTitle) { //一级分类点击
            if (listTotal > 0) {
                this.primaryClassification = false;
                this.secondaryClassification = true;
                this.selectClassificationOneTitleId = categoryId;
                this.primaryTitle = categoryTitle;
                this.getsecondList(categoryId);
            } else {
                if (this.know.kcaIdTwo !== '') {
                    this.know.kcaIdTwo = 0;
                }
                if (this.secondaryTitleShow !== '') {
                    this.secondaryTitleShow = '';
                }
                this.primaryTitleShow = categoryTitle;
                this.selectClassificationTwoOne = true; //在二级分类点击的一级分类
                this.selectClassificationOneTitleId = categoryId; //在二级分类页点击一级分类，保存其id
                this.btnToggleMask = false;
                this.primaryClassification = false;
                this.secondaryClassification = false;
                this.know.kcaIdOne = categoryId;
            }
        },
        /*二级分类显示列表*/
        getsecondList(Id) {
            this.$axios({
                method: 'GET',
                // url: '/app/know/allKnow/kca/NORMAL/' + Id
                url: `/app/api/trainee/know/kca/NORMAL/${Id}`
            }).then((res) => {
                this.questionSecondaryCategory = res.data;
            });
        },
        backToPrevious() { //返回上一级
            this.secondaryClassification = false;
            this.questionSecondaryCategory = [];
            this.primaryClassification = true;
            this.questionPrimaryCategory();
        },
        scCategory(kcaIdTwo, secondTitle) { //二级分类点击
            if (this.primaryTitleShow !== '') {
                this.primaryTitleShow = '';
            }
            this.btnToggleMask = false;
            this.secondaryClassification = false;
            this.primaryClassification = false;
            this.know.kcaIdOne = this.selectClassificationOneTitleId;
            this.know.kcaIdTwo = kcaIdTwo;
            this.secondaryTitleShow = secondTitle;
        },
        maskLayer() { //点击黑块
            this.btnToggleMask = false;
            this.primaryClassification = false;
            this.secondaryClassification = false;
        },
        rewardPoint() { //悬赏积分
            this.rewardPointLayer = true;
        },
        // submitReward() {
        //     if (this.rewPoint <= 0 || isNaN(this.rewPoint) || !/^[1-9]\d*$/.test(this.rewPoint)) {
        //         console.log('tips1.............', this.rewardPointLayer)
        //         this.rewardPointTips1 = true;
        //         this.rewardPointTips2 = false;
        //     } else if (this.rewPoint > this.credits) {
        //         console.log('tips2.............', this.rewardPointLayer)
        //         this.rewardPointTips1 = false;
        //         this.rewardPointTips2 = true;
        //     } else {
        //         console.log('close.............', this.rewardPointLayer)
        //         this.rewardPointTips1 = false;
        //         this.rewardPointTips2 = false;
        //         // this.rewardPointLayer = false;
        //         this.point = this.rewPoint;
        //     }
        // },
        async beforeCloseDialog(action, done) {
            if (action === 'confirm') {
                // 在这里执行你的验证逻辑
                if (this.rewPoint <= 0 || isNaN(this.rewPoint) || !/^[1-9]\d*$/.test(this.rewPoint)) {
                    this.rewardPointTips1 = true;
                    this.rewardPointTips2 = false;
                    done(false); // 阻止对话框关闭
                } else if (this.rewPoint > this.credits) {
                    this.rewardPointTips1 = false;
                    this.rewardPointTips2 = true;
                    done(false); // 阻止对话框关闭
                } else {
                    this.rewardPointTips1 = false;
                    this.rewardPointTips2 = false;
                    this.point = this.rewPoint;
                    this.rewPoint = '';
                    // 如果验证通过，允许对话框关闭
                    done(true);
                }
            } else {
                // 点击取消按钮，直接关闭对话框
                this.rewardPointTips1 = false;
                this.rewardPointTips2 = false;
                this.rewPoint = '';
                done(true);
            }
        },
        queUpFile(event) { //上传文件
            if (['jpg', 'gif', 'jpeg', 'png'].indexOf(event.target.files[0].type.split('/')[1]) === -1) {
                this.$toast(this.$t('lab_file_tips_6'));
                return;
            }
            this.upFile(event, 'Img', 'KnowQuestion', (data, type) => {
                this.upImages.push(data);
            });
            this.$refs.upFile.value = '';
        },
        queDeleteFile(index, id, type) {
            this.deleteFile(id, type, (data, type) => {
                this.upImages.splice(index, 1);
            });
        },
        submit() {
            this.$validator.validate().then(res => {
                if (res) {
                    if (this.isLoading) {
                        return;
                    }
                    this.isLoading = true;
                    // let insructor = [];
                    // let queAskId = [];
                    // for (let item of this.checkedNames) {
                    //     // insructor.push(item.usr_display_bil);
                    //     queAskId.push(item.usr_ent_id);
                    // }
                    // let formData = new FormData();
                    // formData.append('instructor', insructor.join(',')); //用户列表名
                    // formData.append('kcaIdOne', this.know.kcaIdOne); //分类id
                    // formData.append('kcaIdTwo', this.know.kcaIdTwo);
                    // formData.append('queBounty', this.rewPoint); //悬赏积分
                    // formData.append('queContent', this.know.queContent); //简介
                    // formData.append('queTitle', this.know.queTitle); //标题
                    // formData.append('que_ask_ent_ids', queAskId.join(',')); //用户id
                    // formData.append('mobileType', 'MOBILE4.X');
                    this.$axios({
                        method: 'POST',
                        // url: '/app/know/addKnowQuestionMobile',
                        url: `/app/api/trainee/know`,
                        // data: formData
                        data: {
                            // askEntIds: queAskId.join(','),
                            askEntIds: this.checkedNames.join(','),
                            content: this.content,
                            leftCatalogId: this.know.kcaIdOne,
                            queBounty: !this.rewPoint || this.rewPoint === '' ? 0 : this.rewPoint,
                            queIsAnonymous: 'FAIL',
                            queType: 'UNSOLVED',
                            rightCatalogId: this.know.kcaIdTwo,
                            title: this.know.queTitle
                        }
                    }).then(res => {
                        this.$store.commit('removeKeepAliveList', 'KnowIndex');
                        this.$router.replace({name: 'KnowList'});
                    });
                };
            });
        },
        /*下拉刷新*/
        onPulldownTop() {
            this.isTop = false;
            setTimeout(() => {
                this.memberList = [];
                this.pageNo = 1;
                this.getAddMemberList();
            }, 900);
        },
        /*滚动加载*/
        onScrollBottom() {
            if (this.onFetching) {
            } else {
                this.onFetching = true;
                setTimeout(() => {
                    this.onFetching = true;
                    this.pageNo += 1;
                    this.getAddMemberList();
                }, 100);
            }
        },
        /*用户搜索*/
        searchUser() {
            clearTimeout(this.indTime);
            this.indTime = setTimeout(() => {
                this.pageNo = 1;
                this.memberList = [];
                this.getAddMemberList();
            }, 500);
        },
        deleteSearch() {
            if (this.searchContent !== '') {
                this.searchContent = '';
            }
            this.pageNo = 1;
            this.memberList = [];
            this.getAddMemberList();
        },
        getAddMemberList() {
            this.$axios({
                method: 'GET',
                url: '/app/user/getInstructors',
                params: {
                    pageNo: this.pageNo,
                    searchContent: this.searchContent
                }
            }).then(res => {
                if (res.data.rows && res.data.rows.length !== 0) {
                    this.memberList = [...this.memberList, ...res.data.rows];
                }
                this.onFetching = false;
                this.isTop = true;
                this.total = res.data.total;
            });
        },
        selectedUser() {
            this.pageNo = 1;
            this.searchContent = '';
            this.memberList = [];
            this.isShowSelectUser = true;
            // this.getAddMemberList();
        },
        /*退出悬赏积分*/
        cancelPoint() {
            this.rewPoint = this.point;
        }
    },
    mounted() {
        this.$axios({
            method: 'GET',
            // url: '/app/personal/credits/json'
            url: `/app/credit/user`
        }).then((res) => {
            this.credits = res.data;
        });
        this.$axios({
            method: 'GET',
            // url: '/app/know/allKnow/kca/CATALOG/0'
            url: `/app/api/trainee/know/kca/CATALOG/0`
        }).then((res) => {
            this.questionCategory = res.data;
            this.know.kcaIdOne = res.data[0].kcaId;
            this.primaryTitleShow = res.data[0].kcaTitle;
        });
        //清除服务端个人上传的游离文件
        // this.$axios({
        //     method: 'DELETE',
        //     url: '/app/doing/clearInvalidModuleTemplate/',
        //     params: {
        //         module: 'KnowQuestion'
        //     }
        // }).then(res => {});
        //加载图片组件
        this.initPreviewRepair();
    },
    watch: {
        upImages() {
            this.$nextTick(() => {
                this.$previewRefresh();
            });
        },
        searchContent() {
            if (this.searchContent === '') {
                this.deleteSearch();
            }
        }
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        }
    },
    created() {
        this.$Validator.extend('tipsQueTitle', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 400) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        this.$Validator.extend('tipsQueDetail', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 2000) {
                    return false;
                } else {
                    return true;
                }
            }
        });
    }
};
</script>

<style scoped lang="less">
    .module-list-10 li {
        height: 60px;
        line-height: 60px;
        border-bottom: 1px solid #e6e6e6;
        background: #ffffff;
        padding: 0 15px;
    }
    .module-list-10 li:nth-last-child(1) {
        border-bottom: none;
    }
    .arrow-right {
        margin: 25px 0 0 0;
    }
    .mask-layer {
        z-index: 200;
    }
    .word-title-08 {
        float: right;
        margin-right: 5px;
        max-width: 130px;
        overflow: hidden;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .box-16 {
        margin: 0 0 14px;
    }
    .box-16 div {
        height: 42px;
        line-height: 42px;
        padding: 0 15px;
        border: 1px solid #cccccc;
        border-radius: 2px;
        box-sizing: border-box;
        font-size: 14px;
    }
    .box-16 div input {
        float: right;
        width: 80px;
        height: 42px;
        line-height: 42px;
        background: none;
        border: none;
        font-size: 14px;
        text-align: right;
        padding: 0 8px;
    }
    .tips {
        display: inline-block;
        width: 100%;
        min-height: 26px;
        text-align: right;
        line-height: 26px;
    }
    .headerSelect-alert4 ul li.cur {
        color: #075ebb;
    }
    /deep/ .ql-container {
        height: 260px;
    }
    // /deep/ .van-dialog__content {
    //     padding: 10px 30px;
    // }
    // /deep/.van-dialog__header {
    //     padding: 30px 20px 0px
    // }
</style>
